﻿using System;
using System.Collections.Generic;
using System.Linq;
using UMC.Data;
using UMC.ITME.Entities;
using UMC.Net;
using UMC.Web;
using UMC.Web.UI;

namespace UMC.ITME.Activities
{
    [Apiumc("ITME", "Forward", Auth = WebAuthType.All, Desc = "正向代理域名")]
    class SiteForwardActivity : WebActivity
    {

        public override void ProcessActivity(WebRequest request, WebResponse response)
        {
            var key = this.AsyncDialog("Key", g => this.DialogValue("PAC"));
            if (key == "PAC")
            {
                

                var proxyConfig = UMC.Data.Reflection.Configuration("proxy");

                var indexs = new HashSet<int>
                {
                    0
                };

                foreach (var k in proxyConfig.Providers)
                {
                    indexs.Add(Utility.IntParse(Utility.MD5(k.Name.UTF8())));
                }

                var proxys = new List<int>();
                var ms = HotCache.Find(new ProxySite());

                var hash = new List<String>();
                foreach (var m in ms)
                {
                    int index = m.ProxyIP.Int32() ?? 0;
                    if (indexs.Contains(index) == false)
                    {
                        index = 0;
                    }

                    int v = proxys.IndexOf(index);
                    if (v == -1)
                    {
                        if (proxys.Count == 0)
                        {
                            hash.Add("https://exit.proxy.apiumc.com");
                        }
                        else
                        {

                            hash.Add($"https://exit.{proxys.Count}proxy.apiumc.com");
                        }
                        proxys.Add(index);
                    }

                }
                response.Redirect(hash);
            }
            else if (request.IsCashier == false)
            {
                this.Prompt("管理正向代理域名，需要管理员权限");
            }


        }
    }
}